import {Button, Divider, Space, Table, Tag, Modal, message} from "antd";
import {EditOutlined,DeleteOutlined,ExclamationCircleOutlined} from '@ant-design/icons';
import {useEffect, useState} from "react";
import {deleteArticles, getArticles} from "../../api/articles";
import './Table.less'
import {useDispatch, useSelector} from "react-redux";
import {editFilter} from "../../store/filter";
import {useNavigate} from "react-router-dom";
const { confirm } = Modal;


function TableBox(props) {
    //路由
    const navigate=useNavigate()
    //表单规格
    const columns = [
        {
            title: '封面',
            dataIndex: 'cover',
            key: 'cover',
            render: (text, record) => (
                <Space size="middle" className='cover'>
                    {record.cover.type!==0?<img src={record.cover.images[0]} alt='cover'/>:<img src={require('../../assets/logo.536c5d80.png')} alt='cover'/>}
                </Space>
            ),
        },
        {
            title: '标题',
            dataIndex: 'title',
            key: 'title',
            className:'title_style'
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render:(text, record)=>{
                let color =''
                let txt=''
                switch (record.status) {
                    case 0:
                        color='default'
                        txt='草稿'
                        break
                    case 1:
                        color='warning'
                        txt='待审核'
                        break
                    case 2:
                        color='success'
                        txt='审核通过'
                        break
                    default:
                        color='error'
                        txt='审核失败'
                }
                return <Tag color={color}>{txt}</Tag>
            }
        },
        {
            title: '发布时间',
            dataIndex: 'pubdate',
            key: 'pubdate',
        },
        {
            title: '阅读数',
            dataIndex: 'read_count',
            key: 'read_count',
        },
        {
            title: '评论数',
            dataIndex: 'comment_count',
            key: 'comment_count',
        },
        {
            title: '点赞数',
            dataIndex: 'like_count',
            key: 'like_count',
        },
        {
            title: '操作',
            key: 'action',
            render: (text, record) => (
                <Space size="middle">
                    <Button type="primary" shape="circle" icon={<EditOutlined />} onClick={()=>handleEdit(record)}/>
                    <Button type="primary" danger ghost shape="circle" icon={<DeleteOutlined />} onClick={()=>handleRemove(record.id)}/>
                </Space>
            ),
        },
    ]
    //文章列表
    const [data,setData]=useState([])
    //文章总数
    const [count,setCount]=useState()
    //分页状态
    const [page,setPage]=useState(1)
    const [pageSize,setPageSize]=useState(10)
    //筛选信息
    const dispatch=useDispatch()
    const filterInfo=useSelector((state)=>state.filterinfo)
    //初始化
    useEffect(()=>{
      handleArticles()
    },[])
    //根据筛选状态来 获取文章筛选列表
    useEffect(()=>{
         if (filterInfo.isFilter){
             handleArticles(filterInfo.info)
         }
    },[filterInfo.isFilter])
    //获取数据
    const handleArticles=(params)=>{
        getArticles(params).then((res)=>{
            console.log(res)
            if (res.message==='OK'){
                setCount(res.data.total_count)
                setPageSize(res.data.per_page)
                setPage(res.data.page)
                // setData(res.data.results)
                // console.log(res.data.results)
                let obj=[]
                //对数据加工成 符合表单规格的数据
                res.data.results.forEach((item)=>{
                    obj.push({
                        ...item,
                        key:item.id,
                    })
                    // if (item.cover.type===0){
                    //     // setData([...data,{
                    //     //     ...item,
                    //     //     key:item.id,
                    //     //     cover:null
                    //     // }])
                    //     obj.push({
                    //         ...item,
                    //         key:item.id,
                    //         cover:null
                    //     })
                    // }else {
                    //     // setData([...data,{
                    //     //     ...item,
                    //     //     key:item.id,
                    //     //     cover:item.cover.images[0]
                    //     // }])
                    //     obj.push({
                    //         ...item,
                    //         key:item.id,
                    //         cover:item.cover.images[0]
                    //     })
                    // }
                })
                setData(obj)
                // console.log(obj)
            }
        })
        //复原筛选状态 以便下次启动筛选
        if (params){
            dispatch(editFilter({type:false}))
        }
    }
    //删除文章
    const handleRemove=(id)=>{
        confirm({
            title: '温馨提示',
            icon: <ExclamationCircleOutlined />,
            content: '此操作将永久删除该文章, 是否继续？',
            onOk() {
                deleteArticles(id).then((res)=>{
                    if(res.message==='OK'){
                        handleArticles()
                        message.success('删除成功');
                    }
                })
            },
        });
    }
    //编辑文章
    const handleEdit=(e)=>{
        // console.log(e)
        navigate('/home/publish', {state:e})
    }
    //切换分页
    const changePage=(e)=>{
        // console.log(e)
        //启动筛选
        dispatch(editFilter({type:true,info:{page:e}}))
    }
    return (
        <div className='table_box'>
            <div className='table_title'>
                <p>根据筛选条件共查询到 {count} 条结果：</p>
                <Divider plain></Divider>
            </div>
            <Table columns={columns} dataSource={data} pagination={{
                current: page,
                pageSize,
                total: count,
                showSizeChanger: true,
                position: ['bottomCenter'],
                onChange: changePage
            }} className='table_list'/>
        </div>
    );
}

export default TableBox;
